package io.fft.flight.common.channel.jlx;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import io.fft.flight.common.channel.jlx.model.JlxFlight;
import io.fft.flight.common.channel.jlx.model.JlxOrder;
import io.fft.flight.common.channel.jlx.model.JlxPassenger;
import io.fft.flight.common.enums.*;
import io.fft.flight.common.exception.RenExceptionEnum;
import io.fft.flight.common.utils.C;
import io.fft.flight.common.utils.DateUtils;
import io.fft.flight.modules.flight.entity.OrderEntity;
import io.fft.flight.modules.flight.entity.OrderPassengerEntity;
import io.fft.flight.modules.flight.entity.OrderSegmentEntity;
import io.fft.flight.modules.flight.service.OrderPassengerService;
import io.fft.flight.modules.flight.service.OrderSegmentService;
import io.fft.flight.modules.flight.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: likailun
 * @Description: 就旅行渠道
 * @Date: create in 2024/7/9 21:44
 */
@Slf4j
@Component
public class JlxChannel {

    @Resource
    private JlxProp jlxProp;
    @Resource
    private OrderSegmentService orderSegmentService;
    @Resource
    private OrderPassengerService orderPassengerService;
    @Resource
    private OrderService orderService;

    @Transactional
    public void orderExport(OrderExportTypeEnum exportTypeEnum, JiulvxingOrderStatusEnum orderStatusEnum, String start, String end) {
        RenExceptionEnum.NOT_EXIT.assertNotNull(exportTypeEnum);
        RenExceptionEnum.NOT_EXIT.assertNotNull(orderStatusEnum);
        // 查询订单
        XmlMapper xmlMapper = new XmlMapper();
        //TODO 请求接口返回xml
        InputStream inputStream = new InputStream() {
            @Override
            public int read() throws IOException {
                return 0;
            }
        };
        //反序列化为实体对象
        JlxOrder order = null;
        try {
            order = xmlMapper.readValue(inputStream, JlxOrder.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        newOrder(order);
    }

    /**
     * 判断订单是否重复，新订单入库
     * @param order
     * @return
     */
    private boolean newOrder(JlxOrder order){
        if (Objects.isNull(order)) {
            return false;
        }
        final Map<Object, Object> objectObjectHashMap = new HashMap<>();
        orderService.list(new HashMap<>());
        final OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSource(OrderSourceEnum.JLX.getCode());
        orderEntity.setOrderNo(order.getOrderNo());
        orderEntity.setOfficeNo("");
        orderEntity.setPnr(order.getPnr());
        if (null != order.getPayStatus() && order.getPayStatus().equals(1)) {
            orderEntity.setPayType(PayTypeEnum.ALIPAY.getCode());
        }
        orderEntity.setDataSourcePolicyNo(order.getPolicyFid());
        orderEntity.setContactName(order.getSjr());
        orderEntity.setContactTel(order.getContactTel());
        orderEntity.setOrderStatus(order.getStatus());
        orderEntity.setCreateAte(new Date());
        orderService.insert(orderEntity);
        // 乘客信息
        if (C.isNotEmpty(order.getPassenger())) {
            final List<OrderPassengerEntity> passengers = new ArrayList<>();
            for (JlxPassenger jlxPassenger : order.getPassenger()) {
                passengers.add(getOrderPassengerEntity(orderEntity, jlxPassenger));
            }
            orderPassengerService.insertBatch(passengers);
        }
        // 就旅行订单
        if(C.isNotEmpty(order.getFlight())){
            final List<OrderSegmentEntity> segments = new ArrayList<>();
            for (JlxFlight jlxFlight : order.getFlight()) {
                final OrderSegmentEntity segment = new OrderSegmentEntity();
                segment.setOrderNo(orderEntity.getOrderNo());
                segment.setSegmentNo(jlxFlight.getCode());
                segment.setSegmentType(0);
                segment.setFlightNo(jlxFlight.getCode());
                if(StringUtils.isNotEmpty(jlxFlight.getDepDay())){
                    segment.setBeginDate(DateUtils.stringToDate(jlxFlight.getDepDay(),DateUtils.DATE_PATTERN));
                }
                segment.setBeginTime(jlxFlight.getDepTime());
                segment.setArriveDate(null);
                segment.setArriveTime(jlxFlight.getArrTime());
                segment.setSAirportCode(jlxFlight.getDep());
                segment.setEAirportCode(jlxFlight.getArr());
                segment.setCabinCode(jlxFlight.getCabin());
                segment.setCreateDate(new Date());
                segments.add(segment);
            }
            orderSegmentService.insertBatch(segments);
        }
        return true;
    }

    @NotNull
    private OrderPassengerEntity getOrderPassengerEntity(OrderEntity orderEntity, JlxPassenger jlxPassenger) {
        final OrderPassengerEntity passenger = new OrderPassengerEntity();
        passenger.setOrderNo(orderEntity.getOrderNo());
        passenger.setPsgNo("");
        passenger.setPsgName(jlxPassenger.getName());
        if (Objects.nonNull(jlxPassenger.getAgeType())) {
            passenger.setPsgType(jlxPassenger.getAgeType().equals(0) ? PassengerTypeEnum.ADULT.getCode() : (jlxPassenger.getAgeType().equals(1) ? PassengerTypeEnum.CHILDREN.getCode() : PassengerTypeEnum.BABY.getCode()));
        }
        if(StringUtils.isNotEmpty(jlxPassenger.getCardType())){
            passenger.setCardType(getCardTypeEnum(jlxPassenger.getCardType()).getCode());
        }
        passenger.setCardNo(jlxPassenger.getCardNum());
        passenger.setMobile(jlxPassenger.getEticketNum());
        passenger.setBirthday(jlxPassenger.getBirthday());
        if(Objects.nonNull(jlxPassenger.getPrice())){
            passenger.setPersonPrice(jlxPassenger.getPrice().multiply(new BigDecimal(100)).intValue());
        }
        if(StringUtils.isNotEmpty(jlxPassenger.getGender()) && jlxPassenger.getGender().equals("男")){
            passenger.setGender(1);
        }else if(StringUtils.isNotEmpty(jlxPassenger.getGender()) && jlxPassenger.getGender().equals("女")){
            passenger.setGender(2);
        }
        passenger.setCountryCode(jlxPassenger.getNationality());
        passenger.setIssCountryCode(jlxPassenger.getCardIssuePlace());
        if(StringUtils.isNotEmpty(jlxPassenger.getCardExpired())){
            passenger.setCardExpireDate(DateUtils.parse(jlxPassenger.getCardExpired(),"YYYY-MM-DD"));
        }
        passenger.setCreateDate(new Date());
        return passenger;
    }

    private CardTypeEnum getCardTypeEnum(String cardType){
        switch (cardType){
            case "NI":
                return CardTypeEnum.SHEN_FEN_ZHENG;
            case "PP":
                return CardTypeEnum.HU_ZHAO;
            case "ID":
                return CardTypeEnum.OTHER;
            case "HM":
            case "TW":
                return CardTypeEnum.GAT_JMJZZ;
            case "HX":
                return CardTypeEnum.HUI_XIANG_ZHENG;
            case "TB":
                return CardTypeEnum.TAI_BAO_ZHENG;
            case "GA":
                return CardTypeEnum.GA_TXZ;
            case "HY":
                return CardTypeEnum.GJ_HYZ;
            case "JR":
                return CardTypeEnum.JUN_GUAN_ZHENG;
            case "LW":
                return CardTypeEnum.WGR_YJJLZ;
            case "NONE":
                return CardTypeEnum.OTHER;
            default:
                return CardTypeEnum.OTHER;
        }
    }
}
